import React, { useState, useEffect } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import Item from './components/Item/Item'
import './App.css'
export default function App() {
  const [list, setList] = useState([
    {
      id: 2,
      todoName: '吃饭',
      isDone: true,
    },
    {
      id: 1,
      todoName: '睡觉',
      isDone: false,
    },
  ])

  useEffect(() => {
    // 添加任务
    const addId = PubSub.subscribe('add', (topic, todoName) => {
      setList((list) => {
        console.log('list', list.length)
        // 这个list一定是正确的list
        const todo = {
          todoName,
          isDone: false,

          id: list.length ? list[0].id + 1 : 1,
        }

        const newList = [...list]
        newList.unshift(todo)
        // setList的回调中返回什么,则list数据就被改成了什么
        return newList
      })
    })
    return () => {
      PubSub.unsubscribe(addId)
    }
  }, [])

  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {list.map((item) => {
              return <Item key={item.id} todo={item}></Item>
            })}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
